import { View, Text, Image } from '@tarojs/components'
import { useLoad, useDidShow } from '@tarojs/taro'
import { useAuth } from '../../hooks/useAuth'
import { useState } from 'react'
import './index.scss'
import Taro from '@tarojs/taro'
import LoginPop from '../../components/common/LoginPop'

function IconWithFallback({ name, className = 'item-icon' }) {
  const [error, setError] = useState(false)
  const isDev = process.env.NODE_ENV !== 'production'
  if (isDev || error) {
    return (
      <View className='item-icon-placeholder'>
        <Text className='icon-text'>{name.charAt(0).toUpperCase()}</Text>
      </View>
    )
  }
  return (
    <Image
      className={className}
      src={`/assets/images/icons/${name}.png`}
      onError={() => setError(true)}
    />
  )
}

export default function Profile() {
  const { isLoggedIn, userName, login, logout } = useAuth()
  const [showLoginPop, setShowLoginPop] = useState(false)

  useLoad(() => {
    console.log('Profile page loaded.')
  })

  useDidShow(() => {
    console.log('Profile useDidShow (tabBar切换或页面显示)')
    const loginState = Taro.getStorageSync('isLoggedIn')
    const name = Taro.getStorageSync('userName')
    console.log('Profile render, isLoggedIn:', loginState, 'userName:', name)
    console.log('Profile render, isLoggedIn:', isLoggedIn, 'userName:', userName)
    if (!!loginState !== isLoggedIn) {
      if (!!loginState) {
        login(name)
      } else {
        logout()
      }
    }
  })

  const handleLoginClick = () => {
    setShowLoginPop(true)
  }
  const handleLoginSuccess = () => {
    login()
    Taro.showToast({ title: '登录成功', icon: 'success' })
    setShowLoginPop(false)
  }
  const handleClosePop = () => {
    setShowLoginPop(false)
  }

  // 处理已订单点击
  const handleOrderClick = () => {
    if (!isLoggedIn) {
      Taro.showToast({
        title: '请先登录',
        icon: 'none'
      });
      setShowLoginPop(true);
      return;
    }
    
    Taro.navigateTo({
      url: '/pages/order-list/index'
    });
  }

  return (
    <View className='profile-container'>
      {/* 顶部用户信息区域 */}
      <View className='user-info-section'>
        {isLoggedIn ? (
          <>
            <View className='user-avatar-wrapper'>
              <View className='user-avatar-placeholder'>
                <Text>{userName}</Text>
              </View>
            </View>
            <View className='user-details'>
              <Text className='user-name'>欢迎您，{userName}！</Text>
              <Text className='user-motto'>愿你千金无忧，所遇皆是欢喜</Text>
            </View>
          </>
        ) : (
          <View className='user-details'>
            <Text className='user-name login-btn' onClick={handleLoginClick}>登录|注册</Text>
            <Text className='user-motto'>愿你千金无忧，所遇皆是欢喜</Text>
          </View>
        )}
      </View>

      {/* 询价单模块 */}
      <View className='module-section'>
        <View className='module-title'>
          <View className='title-dot'></View>
          <Text className='title-text'>询价单</Text>
          <Text className='see-all'>全部 {'>'}</Text>
        </View>
        <View className='module-content'>
          <View className='module-item'>
            <IconWithFallback name='price-query' />
            <Text className='item-text'>报价中</Text>
          </View>
          <View className='module-item'>
            <IconWithFallback name='price-done' />
            <Text className='item-text'>已报价</Text>
          </View>
          <View className='module-item' onClick={handleOrderClick}>
            <IconWithFallback name='order-done' />
            <Text className='item-text'>已订单</Text>
          </View>
          <View className='module-item'>
            <IconWithFallback name='order-cancel' />
            <Text className='item-text'>已取消</Text>
          </View>
        </View>
      </View>

      {/* 管理模块 */}
      <View className='module-section'>
        <View className='module-title'>
          <View className='title-dot'></View>
          <Text className='title-text'>管理</Text>
        </View>
        <View className='module-list'>
          <View className='list-item'>
            <View className='item-left'>
              <IconWithFallback name='address' />
              <Text className='item-text'>发票地址</Text>
            </View>
            <Text className='item-right'>{'>'}</Text>
          </View>
          <View className='list-item'>
            <View className='item-left'>
              <IconWithFallback name='receipt' />
              <Text className='item-text'>发票信息</Text>
            </View>
            <Text className='item-right'>{'>'}</Text>
          </View>
          <View className='list-item'>
            <View className='item-left'>
              <IconWithFallback name='location' />
              <Text className='item-text'>地址信息</Text>
            </View>
            <Text className='item-right'>{'>'}</Text>
          </View>
          <View className='list-item'>
            <View className='item-left'>
              <IconWithFallback name='certificate' />
              <Text className='item-text'>生产责任证</Text>
            </View>
            <Text className='item-right'>{'>'}</Text>
          </View>
        </View>
      </View>

      {/* 帮助中心 */}
      <View className='help-section'>
        <View className='help-item'>
          <Text className='help-text'>帮助中心</Text>
          <Text className='help-desc'>双击进入联系客服</Text>
          <Text className='item-right'>{'>'}</Text>
        </View>
      </View>

      {/* 仅已登录时显示退出登录按钮，且固定在页面底部 */}
      {isLoggedIn && (
        <View className='logout-btn-fixed'>
          <View className='logout-btn' onClick={logout}>
            <Text>退出登录</Text>
          </View>
        </View>
      )}

      <LoginPop
        visible={showLoginPop}
        onClose={handleClosePop}
        onLogin={handleLoginSuccess}
      />
    </View>
  )
} 